﻿using Ice.Lib.Framework;
using Ice.Lib.Searches;
using Ice.UI.FormFunctions;
using ICSharpCode.SharpZipLib.BZip2;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomizationMaintEntry
{
    public partial class frmCustomizationMaintEntryStandard : Form
    {
        string strDataBase = "";
        string confPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Config\EPICOR.sysconfig");
        string confPathTest = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Config\EPICORTEST.sysconfig");
        Boolean IsAutoSave = false;
        public frmCustomizationMaintEntryStandard(Boolean AutoSave)
        {
            InitializeComponent();
            this.ChkAll.Visible = false;
            strDataBase = DbHelperSQL.QueryDataSet("SELECT DB_NAME()").Tables[0].Rows[0][0].ToString();
            this.Text += "    Data Base:" + strDataBase;
            this.Text += "    Server Name:" + DbHelperSQL.QueryDataSet("SELECT SERVERPROPERTY('MachineName')").Tables[0].Rows[0][0].ToString();
            //this.pan_Pro.Visible = false;
            PubVariable.Login((strDataBase == "EPICOR10" ? confPath : confPathTest), MyData.strEpicorUserID, MyData.strEpicorUserPass, MyData.strEpicorCompany);
            IsAutoSave = AutoSave;
        }

        private void frmCustomizationMaintEntryStandard_Load(object sender, EventArgs e)
        {
            if (IsAutoSave == true)
            {
                this.Visible = true;
                this.Activate();
                btnFind.PerformClick();
                ChkAll.Checked = true;
                btnExport.PerformClick();
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                btnFind.Enabled = false;
                ILauncher IL = new ILauncher(MyData.Session);
                if (MyData.IL == null)
                {
                    throw new Exception("Session未初始化！");
                }
                //Boolean recSelected;
                //string whereClause = " ProductID='EP' AND TypeCode = 'Customization'";
                //DataSet dsAdapter = SearchFunctions.listLookup(MyData.IL, "GenXData", out recSelected, true, whereClause, true);
                //DataTable dt = new DataTable();
                //if (recSelected)
                //{
                //    dt = dsAdapter.Tables[0];
                //}
                //return dt;
                Ice.Adapters.GenXDataAdapter adaGenX = new Ice.Adapters.GenXDataAdapter(IL);

                adaGenX.BOConnect();
                //System.Guid strGuid = new System.Guid("C8A7007A-6B2F-4E8D-9EC0-11C159672E83");

                //adaGenX.GetBySysRowID(strGuid);
                //adaGenX.GetByID("","EP", "Customization","", "ItemCostMarginAnalysis_Gnu", "App.UD20Entry.UD20Form", "");//string company, string productID, string typeCode, string cgcCode, string key1, string key2, string key3);
                //adaGenX.GetByIDEx("EP", "Customization","", "ItemCostMarginAnalysis_Gnu", "App.UD20Entry.UD20Form", "");

                string whereClause1 = " ProductID='EP' AND TypeCode = 'Customization' AND Key1 <>'CustomContextMenu'";//Key1='ItemCostMarginAnalysisPlus'

                SearchOptions opts = new SearchOptions(SearchMode.AutoSearch);
                opts.NamedSearch.WhereClauses.Add("GenXData", whereClause1);
                Boolean MorePages;
                DataSet dtTest = adaGenX.GetListEx(opts, out MorePages);

                //adaGenX.ExportCustmization("", "EP", "Customization", "", "EN_ImportOp", "App.OpMasterEntry.OpMasterForm", "", "", "", @"D:\Desktop\Test2.xml");
                dtTest.Tables[0].DefaultView.RowFilter = whereClause1;
                DataTable dtQuery = dtTest.Tables[0].DefaultView.ToTable();
                this.dataGridView1.DataSource = dtQuery;
                if (!dtQuery.Columns.Contains("xz"))
                {
                    dtQuery.Columns.Add(new DataColumn("xz", typeof(System.Boolean)));
                }
                if (!dtQuery.Columns.Contains("Result"))
                {
                    dtQuery.Columns.Add(new DataColumn("Result", typeof(System.String)));
                }
                for (int intCol = 0; intCol <= this.dataGridView1.Columns.Count - 1; intCol++)
                {
                    //this.dataGridView1.Columns[intCol].SortMode = DataGridViewColumnSortMode.NotSortable;
                    this.dataGridView1.Columns[intCol].ReadOnly = this.dataGridView1.Columns[intCol].Name != "xz";
                }
                this.dataGridView1.Columns["xz"].DisplayIndex = 0;
                this.dataGridView1.Columns["xz"].Width = 30;
                this.dataGridView1.Columns["xz"].HeaderText = "";
                this.dataGridView1.Columns["Company"].Width = 60;
                this.dataGridView1.Columns["SysRowID"].Visible = false;
                this.dataGridView1.Columns["CommentText"].Visible = false;
                adaGenX.Dispose();
                Application.DoEvents();
            }
            catch (Exception ex)
            {
                if (IsAutoSave == false)
                { throw ex; }
            }
            finally
            {
                btnFind.Enabled = true;
                this.ChkAll.Visible = true;
            }
        }

        string strPath = "";
        private void btnExport_Click(object sender, EventArgs e)
        {
            //Thread myThread = new Thread(ExportCustom);
            //myThread.IsBackground = true;
            //myThread.Start(); //线程开始  
            ExportCustom();
        }
        //private delegate void ExportCustomDelegate();
        private void ExportCustom()
        {
            if (this.dataGridView1.DataSource == null) return;
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            try
            {
                objTable.AcceptChanges();
                ILauncher IL = new ILauncher(MyData.Session);
                if (MyData.IL == null)
                {
                    throw new Exception("Session未初始化！");
                }
                //objTable.DefaultView.RowFilter = "xz=1";
                if (objTable.DefaultView.Count <= 0)
                {
                    MessageBox.Show("至少选择一条记录进行打印!");
                    return;
                }
                if (strPath.Trim() == "" && IsAutoSave == false)
                {
                    FolderBrowserDialog diaFB = new FolderBrowserDialog();
                    diaFB.Description = "请选择文件路径";
                    if (diaFB.ShowDialog() == DialogResult.OK)
                    {
                        strPath = diaFB.SelectedPath;
                    }
                    else
                    { return; }
                }
                else if (IsAutoSave == true)
                {
                    strPath = @"D:\CustomAutoBackups";
                    if (!System.IO.Directory.Exists(strPath))
                    {
                        System.IO.Directory.CreateDirectory(@"D:\CustomAutoBackups");
                    }
                    string strCurrDate = DateTime.Now.ToString("yyyyMMdd");
                    if (!System.IO.Directory.Exists(Path.Combine(strPath, strCurrDate)))
                    {
                        System.IO.Directory.CreateDirectory(Path.Combine(strPath, strCurrDate));
                    }
                    strPath = Path.Combine(strPath, strCurrDate);
                }
                //DataTable objTablePrint = objTable.DefaultView.ToTable();
                //objTable.DefaultView.RowFilter = "";
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = objTable.Select("xz=1").Length;
                this.progressBar1.Step = 1;
                this.progressBar1.Value = 0;
                objTable.DefaultView.RowFilter = "xz=1";
                foreach (DataRow row in objTable.DefaultView.ToTable().Rows)
                {
                    if (Convert.ToBoolean(row["xz"]) == true)
                    {
                        //Boolean recSelected;
                        //string whereClause = " ProductID='EP' AND TypeCode = 'Customization'";
                        //DataSet dsAdapter = SearchFunctions.listLookup(MyData.IL, "GenXData", out recSelected, true, whereClause, true);
                        //DataTable dt = new DataTable();
                        //if (recSelected)
                        //{
                        //    dt = dsAdapter.Tables[0];
                        //}
                        //return dt;
                        Ice.Adapters.GenXDataAdapter adaGenX = new Ice.Adapters.GenXDataAdapter(IL);
                        adaGenX.BOConnect();
                        string strFile = "";
                        strFile += strDataBase + "-" + row["Key2"] + "_" + row["TypeCode"] + "_" + row["Key1"] + (row["Description"].ToString().Trim() == "" ? "" : "(" + row["Description"] + ")") + "_" + "CustomExport" + "_" + ToDateTime(row["LastUpdated"]).ToString("yyyyMMdd") + "_" + row["LastUpdatedBy"] + "_" + row["SysCharacter04"];
                        adaGenX.ExportCustmization(row["Company"].ToString(), "EP", "Customization", "", row["Key1"].ToString(), row["Key2"].ToString(), row["Key3"].ToString(), "", "", Path.Combine(strPath, strFile + ".xml"));

                        adaGenX.Dispose();

                        if (this.progressBar1.InvokeRequired == true)
                        {
                            //ExportCustomDelegate objDelegate = ExportCustom;
                            //this.progressBar1.Invoke(objDelegate);
                        }
                        else
                        {
                            this.progressBar1.Value += 1;
                        }
                        Application.DoEvents();
                    }
                }
                if (IsAutoSave == true)
                {
                    System.Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                if (IsAutoSave == false)
                { throw ex; }
            }
            finally
            { objTable.DefaultView.RowFilter = ""; }
        }

        private DateTime ToDateTime(object value)
        {
            DateTime dtValue;
            if (DateTime.TryParse(value.ToString(), out dtValue) == true)
            { return dtValue; }
            return dtValue;
        }

        private void ChkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells["xz"].Value = this.ChkAll.Checked;
            }
        }

        private void chkError_CheckedChanged(object sender, EventArgs e)
        {
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            objTable.AcceptChanges();
            objTable.DefaultView.RowFilter = (chkError.Checked == true ? "Result<>''" : "");
        }

        private void btnSeach_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.DataSource == null) return;
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            ILauncher IL = new ILauncher(MyData.Session);
            if (MyData.IL == null)
            {
                throw new Exception("Session未初始化！");
            }
            try
            {
                objTable.AcceptChanges();
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = objTable.Select("xz=1").Length;
                this.progressBar1.Step = 1;
                this.progressBar1.Value = 0;
                foreach (DataRow row in objTable.Rows)
                {
                    if (Convert.ToBoolean(row["xz"]) == false) { continue; }
                    Ice.Adapters.GenXDataAdapter adaGenX = new Ice.Adapters.GenXDataAdapter(IL);
                    adaGenX.BOConnect();
                    string strTestXXXDef = adaGenX.GetXXXDefContent(row["Company"].ToString(), "EP", "Customization", "", row["Key1"].ToString(), row["Key2"].ToString(), row["Key3"].ToString());
                    adaGenX.Dispose();
                    string[] strSplit = txtName.Text.Trim().Split(',');
                    for (int intRow = 0; intRow <= strSplit.Length - 1; intRow++)
                    {
                        if (strTestXXXDef.ToUpper().IndexOf(strSplit[intRow].ToString().Trim().ToUpper()) >= 0 && strSplit[intRow].ToString().Trim() != "")
                        {
                            if (row["Result"].ToString().Trim() == "")
                                row["Result"] = "Ok";
                        }
                        else
                        {
                            row["Result"] = "";
                        }
                    }
                    row.AcceptChanges();
                    if (this.progressBar1.InvokeRequired == true)
                    {
                        //ExportCustomDelegate objDelegate = ExportCustom;
                        //this.progressBar1.Invoke(objDelegate);
                    }
                    else
                    {
                        this.progressBar1.Value += 1;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objTable.DefaultView.RowFilter = ""; }
        }
    }
}
